package com.icloud.article.boot.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icloud.article.boot.dao.CollectDao;
import com.icloud.article.boot.dto.CollectPageDto;
import com.icloud.article.boot.mapper.CollectMapper;
import com.icloud.article.boot.model.Collect;
import com.icloud.article.boot.model.Discuss;
import com.icloud.article.boot.service.ArticleService;
import com.icloud.article.boot.service.CollectService;
import com.icloud.article.boot.vo.ArticleVo;
import com.icloud.article.boot.vo.CollectVo;
import com.icloud.article.boot.vo.StatisticsVo;
import com.icloud.common.core.api.ResultCode;
import com.icloud.common.database.model.Article;
import com.icloud.common.web.exception.Asserts;
import com.icloud.common.web.util.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 收藏service 实现类
 */

@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {

    @Autowired
    private AuthUtil authUtil;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CollectDao collectDao;

    /**
     * 收藏
     * @param articleId 帖子id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean fav(Long articleId) {
        Article article = articleService.getById(articleId);
        Asserts.fail(null == article, ResultCode.DATA_NOT_EXISTS);

        Long loginId = authUtil.getUserId();

        Collect collect = baseMapper.selectOne(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getCreatedId, loginId)
                .eq(Collect::getArticleId, articleId)
        );
        if(collect!=null){
            return true;
        }

        collect = new Collect();
        collect.setAuthorId(article.getCreatedId());
        collect.setArticleId(articleId);
        collect.setCreatedId(loginId);
        save(collect);
        return true;
    }


    /**
     * 取消收藏
     * @param articleId 帖子id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean cancel(Long articleId) {
        Article article = articleService.getById(articleId);
        Asserts.fail(null == article, ResultCode.DATA_NOT_EXISTS);

        Long loginId = authUtil.getUserId();

        Collect collect = baseMapper.selectOne(new LambdaQueryWrapper<Collect>()
                .eq(Collect::getCreatedId, loginId)
                .eq(Collect::getArticleId, articleId));
        if(collect==null){
            return true;
        }

        baseMapper.deleteById(collect.getId());
        return true;
    }

    /**
     * 查询指定用户收藏分页列表
     * @param dto 分页参数
     * @return
     */
    @Override
    public IPage<ArticleVo> page(CollectPageDto dto) {
        Long customerId = dto.getCustomerId();
        if(customerId==null){
            customerId = authUtil.getUserId();
        }

        IPage<ArticleVo> page = Page.of(dto.getCurrent(), dto.getPageSize());
        IPage<CollectVo> collectPage = collectDao.page(Page.of(dto.getCurrent(), dto.getPageSize()), new LambdaQueryWrapper<Collect>()
                .eq(Collect::getCreatedId, customerId));

        List<CollectVo> records = collectPage.getRecords();
        if(CollectionUtil.isEmpty(records)){
            return page;
        }
        page.setTotal(collectPage.getTotal());

        Set<Long> articleIds = records.stream().map(CollectVo::getArticleId).collect(Collectors.toSet());
        List<ArticleVo> articleVoList = articleService.listVoByIds(articleIds);
        page.setRecords(articleVoList);
        return page;
    }

    @Override
    public Map<Long, Boolean> queryCollect(List<Long> articleIdList) {
        Long loginId = authUtil.getUserId();

        LambdaQueryWrapper<Collect> collectQuery = new LambdaQueryWrapper<>();
        collectQuery.eq(Collect::getCreatedId, loginId);
        collectQuery.in(Collect::getArticleId, articleIdList);
        List<Collect> collectList = baseMapper.selectList(collectQuery);
        List<Long> collectedIdList = collectList.stream().map(Collect::getArticleId).collect(Collectors.toList());
        Map<Long, Boolean> collectMap = new HashMap<>();
        articleIdList.forEach(id->{
            collectMap.put(id, collectedIdList.contains(id));
        });
        return collectMap;
    }

    @Override
    public Map<Long, Long> queryCollectCount(List<Long> articleIdList) {
        LambdaQueryWrapper<Collect> collectQuery = new LambdaQueryWrapper<>();
        collectQuery.in(Collect::getArticleId, articleIdList);
        collectQuery.groupBy(Collect::getArticleId);
        List<StatisticsVo> statisticsVoList = collectDao.queryCollectCountByArticle(collectQuery);
        if (CollectionUtil.isEmpty(statisticsVoList)){
            return new HashMap<>();
        }
        return statisticsVoList.stream().collect(Collectors.toMap(StatisticsVo::getArticleId, StatisticsVo::getCount));
    }
}
